//@author A0081229H
package storage;
import flexiCommands.Clock;
import java.util.Iterator;
import java.util.Timer;
import java.util.TimerTask;

public class OverdueMaintenance {
	private static final int DELAY = 3000;
	private static final int PERIOD = 60000;
	
	private Timer timer;
	private TimerTask task;
	private Storage storage;

	private class MaintainOverdue extends TimerTask {
		@Override
		public void run() {
			// get current system time
			try {
				Date currentDate = Clock.getCurrentDate();
				Time currentTime = Clock.getCurrentTime();
				for (Iterator<Task> it = storage.iterator(); it.hasNext();) {
					Task cTask = it.next();
					Date lastDate = cTask.getDateRange().getEndDate();
					Time lastTime = cTask.getTimeRange().getEndTime();
					if (cTask.getDoneStatus() == false) {
						if (!lastDate.isEmpty()) {
							if (currentDate.compareTo(lastDate) == Helper.MORE) {
								cTask.setOverdue();
							} else if (currentDate.compareTo(lastDate) == Helper.SAME) {
								if (currentTime.compareTo(lastTime) == Helper.MORE) {
									cTask.setOverdue();
								}
							}
						}
					}
				}
			} 		 catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	public OverdueMaintenance() throws NumberFormatException, Exception {
		timer = new Timer();
		task = new MaintainOverdue();
		storage = Storage.getInstance();
	}

	public void start() {
		timer.scheduleAtFixedRate(task, DELAY, PERIOD);
	}
}
